#include "dbase.h"

#include <QHBoxLayout>

dbase::dbase(QObject *parent) :QObject(parent){
}
Identity dbase::mapTo(QString value) {
    if(value == "root") return root;
    else if(value == "admin")return admin;
    else if(value == "user")return user;

    return user;
}
QString dbase::mapTo(Identity value) {
    if(value == 0)return "根管理员";
    else if(value == 1)return "管理员";
    else if(value == 2)return "用户";
    return "用户";
}
bool dbase::openDb(){
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");  //连接本地主机
    db.setPort(3306);
    db.setDatabaseName("agri");//数据库名字
    db.setUserName("root");//账号
    db.setPassword("20030330");//密码
    if (db.open()) return true;
    else return false;
}
bool dbase::insertDb(QString username,QString pass){
    QSqlQuery query(insert_sql_cmd.arg(username,pass),db);
    return query.exec();
}
bool dbase::deleteDb(QString userId){
    QSqlQuery query(delete_sql_cmd.arg(userId),db);
    return query.exec();
}
bool dbase::updateDb1(QString username1,QString username2){
    QSqlQuery query(update_sql_cmd1.arg(username2,username1),db);
    return query.exec();
}
bool dbase::updateDb2(QString username,QString pass){
    QSqlQuery query(update_sql_cmd2.arg(pass,username),db);
    return query.exec();
}
bool dbase::updateDb3(QString userId,QString product,QString device,QString token){
    QSqlQuery query(update_sql_cmd3.arg(product,device,token,userId),db);
    return query.exec();
}
bool dbase::updataDb4(QString userId,QString iden){
    QSqlQuery query(update_sql_cmd4.arg(iden,userId),db);
    return query.exec();
}
int dbase::queryDb(int type,struct_user* list){
    int count = 0;
    if(type == 1){//根据输入查找
        QSqlQuery query(query_sql_cmd1.arg(list->username),db);
        while(query.next()){
            list->userId = query.value(0).toInt();
            list->username = query.value(1).toString();
            list->pass = query.value(2).toString();
            list->x = mapTo(query.value(3).toString());
            list->product = query.value(4).toString();
            list->device = query.value(5).toString();
            list->token = query.value(6).toString();
            count ++;
        }
    }else if(type == 2){//查找全部
        QSqlQuery query(query_sql_cmd2,db);
        while (query.next()) {
            list[count].userId = query.value(0).toInt();
            list[count].username = query.value(1).toString();
            list[count].pass = query.value(2).toString();
            list[count].x = mapTo(query.value(3).toString());
            list[count].product = query.value(4).toString();
            list[count].device = query.value(5).toString();
            list[count].token = query.value(6).toString();
            count ++;
        }
    }
    return count;
}
void dbase::sqlModeInit(QWidget *parent,QTableView *table)
{
    //创建一个QSqlTableModel模型
    sqlTableModel = new QSqlTableModel(parent,db);
    //设置模型表名
    sqlTableModel->setTable("user");
    if(iden){
        sqlTableModel->setFilter("identity= 'user'");
        sqlTableModel->removeColumn(3);
    }
    sqlTableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    sqlTableModel->select();
    table->setModel(sqlTableModel);
}
void dbase::tableviewInit(QTableView *table)
{
    mtable = table;
    table->setSelectionMode(QAbstractItemView::SingleSelection);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    table->setShowGrid(true);
    table->setFocusPolicy(Qt::NoFocus);
    table->setGridStyle(Qt::SolidLine);
    table->setAlternatingRowColors(true);
    table->setContextMenuPolicy(Qt::CustomContextMenu);
    if(!iden){//设置token宽度
       table->setColumnWidth(6,430);
    }else table->setColumnWidth(5,550);
    m_menu = new QMenu(table);
    m_actionAdd = new QAction("添加",m_menu);
    m_actionDel = new QAction("删除",m_menu);
    m_menu->addAction(m_actionAdd);
    m_menu->addAction(m_actionDel);
    connect(m_actionAdd,SIGNAL(triggered()),this,SLOT(slotAdd()));
    connect(m_actionDel,SIGNAL(triggered()),this,SLOT(slotDel()));
    connect(table,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotPopMenu(QPoint)));
}
bool dbase::deleteSqlData(int rowCount){
    sqlTableModel->removeRow(rowCount);
    // 删除前，弹框确认
    int ok = QMessageBox::warning(mtable, "删除当前行！", "确定删除当前行？", QMessageBox::Yes, QMessageBox::No);
    if (ok == QMessageBox::No) {
        sqlTableModel->revertAll();
        return false;
    }
    // 提交
    bool re = sqlTableModel->submitAll();
    // 查询
    sqlTableModel->select();
    return re;
    // bool i = deleteDb(userId);
    // sqlTableModel->select();
    // return i;
}
bool dbase::updataSqlData(QString userId,QString iden){
    bool i = updataDb4(userId,iden);
    sqlTableModel->select();
    return i;
}
bool dbase::updateSqlData(QString userId,QString product,QString device,QString token){
    bool i = updateDb3(userId,product,device,token);
    sqlTableModel->select();
    return i;
}

void dbase::summit(){
    bool z = sqlTableModel->submitAll();
    sqlTableModel->select();
}
void dbase::revert(){
    sqlTableModel->revertAll();
    sqlTableModel->select();
}
/*****槽函数******/
void dbase::slotAdd()
{
    int rowCount = sqlTableModel->rowCount();
    sqlTableModel->insertRow(rowCount);
    mtable->scrollToBottom();
}

void dbase::slotDel()
{
    int rowCount = sqlTableModel->rowCount();
    // 删除前，弹框确认
    int ok = QMessageBox::warning(mtable, "删除当前行！", "确定删除当前行？", QMessageBox::Yes, QMessageBox::No);
    if (ok == QMessageBox::No) {
        sqlTableModel->revertAll();
        return;
    }
    sqlTableModel->removeRow(rowCount - 1);
}
void dbase::slotPopMenu(QPoint p)
{
    QModelIndex index = mtable->indexAt(p);//获取鼠标点击位置项的索引
    if(index.isValid())//数据项是否有效，空白处点击无菜单
    {
        if(index.column()!= 3){
            m_menu->exec(QCursor::pos());//显示菜单
        }
    }
}
